package com.abby.socket;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class SocketDemo {
    private static final String HOST_NAME="www.baidu.com";
    private static final String SAVE_PATH="F:"+File.separator+"test.txt";

    public static void main(String[] args) {
        try {
            //open socket
            //打开socket
            Socket socket = new Socket(InetAddress.getByName(HOST_NAME),80);
            if (socket.isConnected()){
               System.out.println("connected to "+HOST_NAME);
            }

            //indicate protocol
            //发送HTTP请求
            PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
            writer.println("GET / HTTP/1.1");
            writer.println("\r\n");

            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String line;

            //read the content
            //读取网页内容
            while((line=br.readLine())!=null){
                builder.append(line);
            }


            File file =new File(SAVE_PATH);
            File parentFile = file.getParentFile();
            if(!parentFile.exists()){
                parentFile.mkdirs();
            }
            if(!file.exists()){
                file.createNewFile();
            }

            //write content to given file
            //往指定文件中写入内容
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(file));
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(builder.toString());
            bufferedWriter.flush();
            bufferedWriter.close();

            if(!socket.isClosed()){
                socket.close();
            }
            writer.close();
            br.close();
        } catch (IOException e){
           e.printStackTrace();
        }
    }
}
